<template>
  <!-- 关联渠道订单弹窗 开始 -->
  <el-dialog
    :visible.sync="dialogFormVisible"
    :before-close="handleClose"
    :show-close="true"
    :append-to-body="false"
    :class="{'mobile-el-dialog': showMobilePage}"
    title=""
    class="large-common-dialog-size related-order-dialog"
    center
    @open="openDialog">
    <div class="main">
      <div :style="{maxHeight: maxHeight}" class="dialog-scroll">
        <div class="title-wrap">
          <Title :is-show="true" :total="listData.total" font-size="16px" title="商品与订单" />
        </div>
        <div v-if="data.length > 0" :class="{'mobile-el-form': showMobilePage}" class="header-form">
          <el-form class="customer-form" label-width="100px" label-position="right">
            <el-row :class="{'el-form-dividing-2': !showMobilePage}" class="content">
              <el-col :span="12">
                <el-form-item label="订单号：" style="margin-bottom: 0px;">
                  <ToolTip v-if="data[getTitleIndex('订单号')]" :content="returnTarget('订单号')"/>
                  <div v-else>--</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品名称：" style="margin-bottom: 0px;">
                  <ToolTip v-if="data[getTitleIndex('商品名称')]" :content="returnTarget('商品名称')" class="max-width-130"/>
                  <div v-else>--</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单状态：" style="margin-bottom: 0px;">
                  <ToolTip v-if="data[getTitleIndex('订单商品状态')]" :content="returnTarget('订单商品状态')"/>
                  <div v-else>--</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品类型：" style="margin-bottom: 0px;">
                  <ToolTip v-if="data[getTitleIndex('商品类型')]" :content="returnTarget('商品类型')"/>
                  <div v-else>--</div>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="code-id">
                <el-form-item label="商品规格ID：" style="margin-bottom: 0px;">
                  <div class="flex-center">
                    <ToolTip v-if="data[getTitleIndex('商品规格ID')]" :content="returnTarget('商品规格ID')" />
                    <div v-else>--</div>
                    <div class="checkbox-style"><el-checkbox v-model="specificationCodeIdRead" @change="fetchData(true)"><span style="font-size:14px;">只读</span></el-checkbox></div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品ID：" style="margin-bottom: 0px;">
                  <div class="flex-center">
                    <ToolTip v-if="data[getTitleIndex('商品ID')]" :content="returnTarget('商品ID')" />
                    <div v-else>--</div>
                    <div class="checkbox-style"><el-checkbox v-model="goodsIdRead" @change="fetchData(true)"><span style="font-size:14px;">只读</span></el-checkbox></div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- <div class="line">&nbsp;</div> -->
        </div>
        <div v-loading="listLoading" :style="{ 'min-height': (showMobilePage && data.length) && 'unset' }" class="table-list">
          <el-row>
            <el-table
              v-if="listData.items.length > 0"
              :data="listData.items"
              :ref="tableRefName"
              :row-class-name="(data) => tableRowClassName(data)"
              :height="showMobilePage && data.length ? '150' : '300'"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              header-cell-class-name="order-data-header-cell"
              fit
              hightlight-current-row>
              <el-table-column
                fixed
                align="center"
                label="选择商品"
                width="80" >
                <template slot-scope="scope">
                  <el-radio v-model="id" :label="scope.row[8]" />
                </template>
              </el-table-column>
              <el-table-column
                v-for="(titleItem, tIndex) in listData.titles"
                :key="titleItem + tIndex"
                :label="titleItem"
                :prop="titleItem"
                :fixed="false"
                :min-width="titleItem === '供货价（人工）' ? 150 : (titleItem === '商品归属-人工' ? 120 : 90)"
                :width="titleItem === '_id'? '1' : 'auto' "
                align="left"
              >
                <template slot-scope="scope">
                  <div v-if="scope.column.label === '供货价（人工）'" class="flex-center">
                    <ToolTip :content="scope.row[tIndex]"/>
                  </div>
                  <div v-else-if="scope.column.label === '商品归属-人工'" class="flex-center edit-area goods-type">
                    <div v-if="scope.row[tIndex]" class="text-wrap"> {{ scope.row[tIndex] }}</div>
                    <div v-else class="text-wrap">--</div>
                  </div>
                  <div v-else-if="scope.column.label === '供应商名称'" class="flex-center edit-area width-100-precent">
                    <ToolTip :content="scope.row[tIndex]"/>
                  </div>
                  <div v-else class="flex-center width-100-precent">
                    <ToolTip :content="scope.row[tIndex]"/>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <empty-placeholder v-else style="margin-bottom: 24px" />
          </el-row>
        </div>
      </div>
      <div v-if="showMobilePage" style="padding: 10px 24px 0;">
        <el-pagination
          :current-page="listData.page"
          :page-size="listData.perPage"
          :total="listData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev,next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
      <div v-if="listData.items.length > 0" class="footer-container">
        <div class="btn-area">
          <el-button :loading="submitLoading" type="primary" size="small" class="submit-btn" @click="goodsConfirm">确认</el-button>
          <el-button class="cancel-btn-style" type="info" @click="handleClose">取 消</el-button>
        </div>
        <div v-if="!showMobilePage" class="pagination-area">
          <el-pagination
            :current-page="listData.page"
            :page-size="listData.perPage"
            :total="listData.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 关联渠道订单弹窗 -->
</template>

<script>
// 表格列表数据
import { mapState } from 'vuex';
import { hasRouteAuth } from '@/utils/permission';
// 组件
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
// api
import { getGoodsOrderAssociatedGoodsList, goodsConfirm } from '@/api/commerce';
// filter
import {
  costTypeFilter,
  orderTypeStatusFilter,
  setReviewState,
  orderStatusFilter } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormatNoHour, format } from '@/filters/date';
/**
 * returnTarget 根据 标题 获取 listData中的 title的索引 用来获取对应数据 ， 所以 已和产品约定好title名称不能
 * **/
export default {
  name: 'GoodsConfirmDialog',
  components: {
    Title,
    EmptyPlaceholder },
  filters: {
    costTypeFilter,
    orderTypeStatusFilter,
    setReviewState,
    moneyFilter,
    standardFormatNoHour,
    format,
    orderStatusFilter },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    // 回填数据
    data: {
      type: Array,
      default: () => []
    },
    orderNums: {
      type: String,
      default: ''
    },
    // 商品id
    goodsId: {
      type: String,
      default: ''
    },
    // 商品规格Id
    specificationCodeId: {
      type: String,
      default: ''
    },
    titles: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      tableRefName: 'orderGoodsTable',
      paramsObj: {},
      id: '',
      listLoading: false,
      submitLoading: false,
      listData: {
        items: []
      },
      page: 1,
      perPage: 20,
      goodsIdRead: false,
      specificationCodeIdRead: false,
      maxHeight: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  created() {
  },
  activated() {
  },
  methods: {
    hasRouteAuth,
    handleClose() {
      this.id = '';
      this.initParams();
      this.$emit('close', '');
    },
    openDialog() {
      this.id = this.data[this.data.length - 1];
      this.goodsIdRead = false;
      this.specificationCodeIdRead = false;
      const clientHeight = window.innerHeight;
      this.maxHeight = this.showMobilePage ? (clientHeight * 2.8) / 5 + 'px' : '450px';
      this.fetchData(true);
    },
    initParams() {
      this.paramsObj = {};
    },
    getTitleIndex(title) {
      const index = this.titles.indexOf(title);
      return index;
    },
    returnTarget(title) {
      const index = this.titles.indexOf(title);
      if (index >= 0) {
        return this.data[index];
      } else {
        return '--';
      }
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const { goodsId, specificationCodeId, page, perPage } = this;
      const params = {
        readFlag: false,
        page,
        perPage
      };
      if (this.goodsIdRead) {
        params.goodsId = goodsId;
      }
      if (this.specificationCodeIdRead) {
        params.specificationCodeId = specificationCodeId;
      }
      if (!this.goodsIdRead && !this.specificationCodeIdRead) {
        params.specificationCodeId = specificationCodeId;
        params.goodsId = goodsId;
      }
      if (this.goodsIdRead && this.specificationCodeIdRead) {
        params.readFlag = true;
      }
      this.listLoading = true;
      getGoodsOrderAssociatedGoodsList(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          this.listData = res.data;
        }
      }).catch(e => {
        this.listLoading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    // 确认商品
    goodsConfirm() {
      const { id, orderNums } = this;
      if (this.submitLoading) return;
      if (!id) {
        this.$message.warning('请选择确认的商品！');
        return false;
      }
      const params = {
        _id: id,
        orderNums
      };
      this.submitLoading = true;
      goodsConfirm(params).then(res => {
        this.$message.success('关联成功');
        // 将选择的订单id传送给父组件
        this.$emit('success', id);
        this.handleClose();
        this.submitLoading = false;
      }).catch(err => {
        this.submitLoading = false;
        console.error(err);
      });
    },
    tableRowClassName({ row, rowIndex }) {
      return this.id === row[8] ? `table-selected` : '';
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  ::v-deep .el-form-item__content {
    height: 32px;
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.checkbox-style {
  margin-left: 20px;
  line-height: 25px;
}
.related-order-dialog {
  ::v-deep {
    .el-dialog__body {
      padding: 24px 0 24px 0 !important;;
    }
    .el-icon {
      color: #999;
    }
    .el-radio__label {
      display: none;
    }
    .select-input-component .el-input>.el-input__inner {
      width: 160px;
    }
    .el-form-item {
      margin-bottom: 0;
    }
    .el-form-item__label {
      color: #999;
      padding-right: 5px;
    }
    .el-form-item__content {
      color: #333;
    }
    .el-table {
      th>.cell {
        color: #141C3D;
      }
    }
  }
  &.mobile-el-dialog {
    .footer-container {
      margin-top: 16px;
      justify-content: center;
    }
  }
}
.el-pagination {
  padding: 0 !important;
}
.main {
  position: relative;
  height: 485px;
}
.header-form {
  position: relative;
  padding: 0 24px;
  margin-bottom: 7px;
}
.title-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px 7px;
}
.table-list {
  padding: 0 24px;
  min-height: 300px;
}
.max-width-130 {
  max-width: 130px;
}
.max-width-200 {
  max-width: 200px;
}

.el-table::before {
  display: none;
}
.dialog-scroll {
  min-height: 350px;
  @include scrollBar();
}
.submit-btn {
  height: 30px;
}
.cancel-btn-style {
  padding: 0;
  width: 80px;
  height: 30px;
  font-size: 14px;
  box-sizing: border-box;
}
.footer-container{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 24px 0;
}
.overflow {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}
.btn-area {
  display: flex;
}
.line {
  margin: 18px 0 8px -24px;
  width: 960px;
  height: 6px;
  background: #F7F7F7;
  font-size: 0;
}
</style>
